package net.tp.fractal;

import java.awt.Color;
import java.awt.image.BufferedImage;

public class Mandelbrot {

    public static int mand(double re0, double im0, int max) {
    	double re = re0;
    	double im = im0;
    	
        for (int t = 0; t < max; t++) {
        	double abs = Math.hypot(re, im);
        	if (abs > 2.0) {
        		return t;
        	}
        	double newRe = re0 + re*re - im*im;
        	double newIm = 2 * re * im + im0;
        	re = newRe;
        	im = newIm;
        }
        return max;
    }

    public static BufferedImage generate(int N, double xc, double yc, double size) {

        int max = 255;   // maximum number of iterations

        BufferedImage image = new BufferedImage(N, N, BufferedImage.TYPE_INT_BGR);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                double x0 = xc - size/2 + size*i/N;
                double y0 = yc - size/2 + size*j/N;
                int gray = max - mand(x0, y0, max);
                Color color = new Color(gray, gray, gray);
                image.setRGB(i, j, color.getRGB());
            }
        }

        return image;

    }

	
}
